package com.cckj.projectapi.framework.config.security;

import com.cckj.projectapi.framework.util.SecurityUtils;
import com.cckj.common.base.LoginUserEntity;
import com.cckj.common.exception.BusinessException;
import com.cckj.common.response.ResultData;
import com.cckj.common.service.JwtTokenService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    JwtTokenService jwtTokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        String header = request.getHeader(jwtTokenService.getHeader());
        if (StringUtils.isBlank(header)){
            filterChain.doFilter(request, response);
            return;
        }
        if (SecurityUtils.getAuthentication() == null) {
            LoginUserEntity loginUser = jwtTokenService.getLoginUser(request);
            if (loginUser == null) {
                response.getWriter().write(new ObjectMapper().writeValueAsString(ResultData.error(403, "非法请求")));
                return;
            }
            log.info("用户：{} ，tokenId：[{}] 认证通过", loginUser.getName(), loginUser.getToken());

            // 验证令牌有效期，相差不足20分钟，自动刷新缓存
            try {
                jwtTokenService.verifyToken(loginUser);
            } catch (BusinessException e) {
                response.getWriter().write(new ObjectMapper().writeValueAsString(ResultData.error(403, e.getMessage())));
                return;
            }
            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(loginUser, null, Lists.newArrayList());

            authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authToken);
        }
        filterChain.doFilter(request, response);
    }
}
